package com.llkj.qingnianguoxue.home;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.adapter.MasterPayAdapter;
import com.llkj.qingnianguoxue.base.BaseActivity;
import com.llkj.qingnianguoxue.base.ConstantUserInfo;
import com.llkj.qingnianguoxue.bean.ExchangeBean;
import com.llkj.qingnianguoxue.bean.MasterSubcribeBean;
import com.llkj.qingnianguoxue.customview.ExpandGridView;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.ImageLoadingUtil;
import com.llkj.qingnianguoxue.util.PayMethodViewUtil;
import com.llkj.qingnianguoxue.util.RxBus;
import com.llkj.qingnianguoxue.util.StringUtils;
import com.llkj.qingnianguoxue.util.ToastUtil;
import com.pingplusplus.android.Pingpp;
import com.sevenheaven.iosswitch.ShSwitchView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;

/**
 * 订阅大师
 */
public class MasterSubscribeActivity extends BaseActivity implements View.OnClickListener,PayMethodViewUtil.PaySuccessListener {
    private ImageView ivHead;//头像
    private TextView tvName, tvCount, tvDescription;//名字，订阅数，j简介
    private ExpandGridView gvPay;//支付
    private MasterPayAdapter masterPayAdapter;//支付
    private List<MasterSubcribeBean.PriceBean> payData;//支付数据
    private TextView btnPay;//支付
    private String mMasterId;//大师id
    private String mPayMoney,mActualMoney,mDeductionMoney = "0";//要支付的金额,实际支付,抵扣金额
    private TextView tvTotalMoney,tvDeduction,tvActualMoney;//总价，抵扣，实际支付
    private ShSwitchView swOpenBtn;//抵扣开关
    private PayMethodViewUtil payMethodViewUtil;
    private String mPayIntegral = "0";//兑换的积分数

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_master_subscribe);
        setTitle("订阅", true, TITLE_TYPE_IMG, R.drawable.icon_back, false, -1, -1);
        initStatusbar(TSATUSBAR_TYPE_BLACK_TEXT,rlTitle,R.color.colorFAF9F9);

        ButterKnife.bind(this);
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            mMasterId = bundle.getString("id");
        }

        initView();
        initListener();
        payMethodViewUtil = new PayMethodViewUtil(this,this);

        loadWaitDialog();
        HttpMethod.artistSubscription(this, this, mMasterId);
    }

    private void initView() {
        ivHead = (ImageView) findViewById(R.id.iv_head);
        tvName = (TextView) findViewById(R.id.tv_name);
        tvCount = (TextView) findViewById(R.id.tv_buy_count);
        tvDescription = (TextView) findViewById(R.id.tv_introduction);
//        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ivHead.getLayoutParams();
//        params.height = DisplayUtil.dip2px(this, 100) * 200 / 162;

        tvTotalMoney = (TextView) findViewById(R.id.tv_total_money);
        tvDeduction = (TextView) findViewById(R.id.tv_deduction_money);
        tvActualMoney = (TextView) findViewById(R.id.tv_pay_money);
        swOpenBtn = (ShSwitchView) findViewById(R.id.sw_open);
        swOpenBtn.setOn(false);

        gvPay = (ExpandGridView) findViewById(R.id.gv_pay);
        payData = new ArrayList<>();

        masterPayAdapter = new MasterPayAdapter(this, payData);
        gvPay.setAdapter(masterPayAdapter);

        btnPay = (TextView) findViewById(R.id.tv_pay);

    }

    private void initListener() {
        gvPay.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MasterSubcribeBean.PriceBean item = payData.get(position);
                masterPayAdapter.setCheckPosition(position);
                mPayMoney = item.getPrice();
                changeMoney();
            }
        });
        btnPay.setOnClickListener(this);
        swOpenBtn.setOnSwitchStateChangeListener(new ShSwitchView.OnSwitchStateChangeListener() {
            @Override
            public void onSwitchStateChange(boolean isOn) {
                changeMoney();
            }
        });
    }

    /**
     * 当付费方式变化，重新计算付款金额
     */
    private void changeMoney(){
        tvTotalMoney.setText(mPayMoney+"银子");
        mActualMoney = mPayMoney;
        if(swOpenBtn.isOn()){
            try{
                mActualMoney = String.format("%.2f",Float.parseFloat(mPayMoney)-Float.parseFloat(mDeductionMoney));
            }catch (Exception e){
                mActualMoney = mPayMoney;
            }
        }

        tvActualMoney.setText(mActualMoney+"银子");

        if(Float.parseFloat(mDeductionMoney)<=0){
            tvDeduction.setText("物品金额未达到使用积分标准");
        }else{
            tvDeduction.setText(String.format(getString(R.string.course_deduction_money),mPayIntegral,mDeductionMoney));
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_pay:
                payMethodViewUtil.showPayMethodDialog(mActualMoney);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        payMethodViewUtil.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void paySucessResponse(int type) {
        //处理三方支付成功后的操作
        payMaster("1");
    }

    private void payMaster(String way) {
        loadWaitDialog();
        String is_integral = swOpenBtn.isOn()?"2":"1";
        MasterSubcribeBean.PriceBean item = payData.get(masterPayAdapter.getCheckPosition());
        HttpMethod.artistBuy(this, this, mMasterId, way, item.getId(), mPayMoney, is_integral,mPayIntegral);
    }

    private void userExchange(){
        HttpMethod.userExchange(this,this,mPayMoney);
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
        if (method == HttpMethod.HTTP_ARTIST_SUBSCRIPTION) {//4.5订阅大师页面
            MasterSubcribeBean subcribeBean = GsonUtil.GsonToBean(data, MasterSubcribeBean.class);
            if (subcribeBean != null) {
                ImageLoadingUtil.loadingImg(ivHead, subcribeBean.getImg(), 0);
                tvName.setText(subcribeBean.getName());
                tvDescription.setText(subcribeBean.getAbstractX());
                String count = subcribeBean.getOrder_num() + "人订阅";
//                SpannableString sp = TextViewUtil.getForegroundColorSpan(this, count, 0, subcribeBean.getOrder_num().length(), getResources().getColor(R.color.colorC49F4A));
                tvCount.setText(count);

                payData.addAll(subcribeBean.getPrice());
                masterPayAdapter.notifyDataSetChanged();

                MasterSubcribeBean.PriceBean item = payData.get(0);
                mPayMoney = item.getPrice();
                changeMoney();
                userExchange();
            }
        }else if (method == HttpMethod.HTTP_PUB_USER_EXCHANGE) {//范儿币抵扣
            ExchangeBean exchangeBean = GsonUtil.GsonToBean(data,ExchangeBean.class);
            if(exchangeBean != null){
                mPayIntegral = exchangeBean.getMax_integral();
                mDeductionMoney = exchangeBean.getMax_exchange();
                changeMoney();
            }
        } /*else if (method == HttpMethod.HTTP_YOUR_URL) {//获取支付参数
            try {
                JSONObject jsonObject = new JSONObject(data);
                if (jsonObject.has("error")) {
                    jsonObject = jsonObject.getJSONObject("error");
                    String message = jsonObject.getString("message");
                    dialogPrompt(message, null, "知道了");
                } else {
                    Pingpp.createPayment(this, data);//调起支付控件
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }*/ else if (method == HttpMethod.HTTP_ARTIST_ARTIST_BUY) {//9.4定购大师/APP
            RxBus.getInstance().post(ConstantUserInfo.REFRESH_SUBSCRIBE);
            setResult(RESULT_OK);
            myFinish();
        }
    }

    @Override
    protected void myToast() {
        super.myToast();
        ToastUtil.makeLongText(this, "订阅成功");
    }

    @Override
    protected void onhttpFailed(String message, int method) {
        dismissWaitDialog();
        if (method != HttpMethod.HTTP_PUB_USER_EXCHANGE && !StringUtils.isEmpty(message)) {
            ToastUtil.makeLongText(this, message);
        }
    }
}
